package com.rk.pethome.user.controller;
import com.rk.pethome.basic.util.AjaxResult;
import com.rk.pethome.user.Service.IWechatService;
import com.rk.pethome.user.constant.WechatConstant;
import com.rk.pethome.user.domain.User;
import com.rk.pethome.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信相关的controller
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private IWechatService wechatService;


    /**
     * 跳转到登录界面(拉取二维码)
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        //获取授权码的url地址(拉取二维码）
        String codeUrl = WechatConstant.CODEURL.
                replace("APPID", WechatConstant.APPID)
                .replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
        return "redirect:"+codeUrl;
    }


    /**
     * 扫码成功之后，自动调用这个接口
     * @param code
     * @return
     */
    @RequestMapping("/callback")
    public String callback(String code){
        System.out.println("授权码:"+code);
        return "redirect:http://localhost:8082/callback.html?code="+code;
    }


    /**
     * 跳转到绑定界面，或者直接的登录
     * 通过code获取token
     * @param
     */
    @RequestMapping("/gotoBinderOrLogin")
    @ResponseBody
    public Map<String, Object> gotoBinderOrLogin(@RequestBody Map<String,String> param) throws UnsupportedEncodingException {
        //获取授权码
        String code = param.get("code");
        //通过授权码获取token
         return wechatService.gotoBinderOrLogin(code);
    }


    /**
     * 绑定用户
     * @param
     * @return
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody HashMap<String,String> param){
        try {
            return wechatService.binder(param);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }
    }

}
